# -*- conding:UTF-8 -*-

'''
@ Project: P7_5group_lotk
@ File: Channel_view.py
@ Author: 罗婷
@ Date：2022/6/9 10:10
频道相关的 视图
'''
import json

from flask import Blueprint, jsonify, g
from flask_restful import Api, Resource, reqparse, marshal
from common.model_fields.channls import channls_fields, news_fields, comment_fields, user_fields
from common.utils.login_utils import login_qlvi
from models.user import *

channel_bp = Blueprint('channel_bp', __name__, url_prefix='/v1_1')
api = Api(channel_bp)


# 获取全部频道
class ChannelsAll(Resource):

    def get(self):
        channel = Channel.query.all()
        marshal_channel = marshal(channel, channls_fields)
        print('marshal_channel 频道数据:', marshal_channel)
        return jsonify(msg='获取所有频道成功', code=200, data=marshal_channel)

# 获取我的频道
# class MyChannels(Resource):
#     @login_qlvi
#     def get(self):
#         uid = g.user_id
#         print('g.user_id是否存在', uid)
#         mycha = UserChannel.query.filter_by(uid=uid).all()
#         marshal_channel = marshal(mycha, channls_fields)
#
#         print('marshal_channel 频道数据:', marshal_channel)
#         return jsonify(msg='获取用户关注频道成功', code=200, data=marshal_channel)


# 获取文章
class NewsAll(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('channel_id')
        args = parser.parse_args()
        cid = args['channel_id']
        print('前端传来的channel_id', cid)
        news = News.query.filter_by(channel_id=cid).all()
        marshal_news = marshal(news, news_fields)
        print('marshal_news 文章数据:', marshal_news)
        return jsonify(msg='获取文章成功', code=200, data=marshal_news)

# 获取文章详情  用户头像 姓名 时间
# @login_qlvi
class Newsdetail(Resource):
    def get(self, nid):
        # uid = g.user_id
        # print('强制登录的g对象id', uid)
        print('前端获取的文章id', nid)
        new = News.query.filter_by(nid=nid).first()
        marshal_new = marshal(new, news_fields)
        print('marshal_news 文章数据:', marshal_new)
        user = UserModel.query.filter_by(uid=new.user_id).first()
        userinfo = {'uname': user.uname, 'profile_photo': user.profile_photo}
        marshal_new.update(userinfo)

        return jsonify(msg='获取文章成功', code=200, data=marshal_new)

#评论
class Comments_view(Resource):
    # 展示评论  用户头像 用户昵称     评论内容 评论时间 回复条数  source
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('source')
        parser.add_argument('type')
        args = parser.parse_args()
        source = args['source']
        type = args['type']
        print('前端传来的source', source)
        if type == 'a':
            coms = Comment.query.filter_by(article_id=source, parent_id=None).all()
            comments = json.loads(json.dumps(marshal(coms, comment_fields)))  # 列表套字典
            print('展示评论comments', comments)

            for i in comments:
                user = UserModel.query.filter_by(uid=i['user_id']).first()
                # print('!!!!!!user====', user, type(user))
                print('!!!!!!user.uname====', user.uname)
                userinfo = marshal(user, user_fields)
                i['userinfo'] = userinfo
            return jsonify(smg='获取评论成功', code=200, data=comments)

        if type == 'c':
            # 获取子评论
            coms_ = Comment.query.filter_by(parent_id=source).all()
            print('紫皮能录~~~~~', coms_)
            comments_ = json.loads(json.dumps(marshal(coms_, comment_fields)))  # 列表套字典
            for g in comments_:
                user = UserModel.query.filter_by(uid=g['user_id']).first()
                userinfo = marshal(user, user_fields)
                g['userinfo'] = userinfo
            return jsonify(smg='获取评论成功', code=200, data=comments_)


        # print('这里是最终评论信息comments', comments)
        # return jsonify(smg='获取评论成功', code=200, data=comments)
    # 获取评论

    # def get(self):
    #     parser = reqparse.RequestParser()
    #     parser.add_argument("source")
    #     parser.add_argument("offset")
    #     args = parser.parse_args()
    #     article_id = args["source"]
    #     # parent_id = args["offset"]
    #     comment1 = Comment.query.filter_by(article_id=article_id, parent_id=None).all()
    #     comment1_list = []
    #     for i in comment1:
    #         comment_mar = marshal(i, comment_fields)
    #         print("comment_", comment_mar)
    #         comment2 = Comment.query.filter_by(parent_id=i.cmid).all()
    #         print("comment2", comment2)
    #         user1 = UserModel.query.filter_by(uid=i.user_id).first()
    #         comment2_list = []
    #         for j in comment2:
    #             user2 = UserModel.query.filter_by(uid=j.user_id).first()
    #
    #             comment2 = marshal(j, comment_fields)
    #             comment2["user"] = marshal(user2, user_fields)
    #             comment2_list.append(comment2)
    #         comment_mar["parent"] = comment2_list
    #         comment_mar["user"] = marshal(user1, user_fields)
    #
    #         comment1_list.append(comment_mar)
    #     return jsonify(message="获取评论成功", code=200, data=comment1_list)

    @login_qlvi
    # 发布评论  target 文章id   content评论内容
    def post(self):
        print('g.user_id,',g.user_id)
        parser = reqparse.RequestParser()
        argss = ['content', 'target', 'art_id']
        for i in argss:
            parser.add_argument(i)
        args = parser.parse_args()
        content = args['content']
        nid_p = args['target']
        nid = args['art_id']
        if not all([content, nid_p, nid]):  #评论文章  传入文章id 用户id
            try:
                print(">>>>>>>>>>>>>",content, nid_p, nid)
                comment = Comment(article_id=nid_p, content=content, user_id=g.user_id)
                db.session.add(comment)
                db.session.commit()
            except:
                return jsonify(msg='评论失败', code=400)
            return jsonify(msg='评论文章成功', code=200)
        else:
            try:
                comment = Comment(article_id=nid, content=content, parent_id=nid_p, user_id=g.user_id)
                db.session.add(comment)
                db.session.commit()
            except:
                return jsonify(msg='评论失败', code=400)
            return jsonify(msg='回复评论成功', code=200)



api.add_resource(ChannelsAll, '/channels')
# api.add_resource(MyChannels, '/my_channels')
api.add_resource(NewsAll, '/articles')
api.add_resource(Newsdetail, '/articles/<int:nid>')
api.add_resource(Comments_view, '/comments')















